import { throttle } from "lodash-es";
import { createEffect } from "solid-js";
import { createStore } from "solid-js/store";
import { useableState } from ".";
export type doState = "doing" | "done" | "pause" | "";
type PlanItem = {
  text: string;
  /**进度百分比 */
  schedulePercent: string;
  /**进行状态 */
  doState: doState;
};
type WorkStore = {
  [id: string]: PlanItem[];
};
let initValueStr = localStorage.getItem("workPlan");
if (initValueStr == null) {
  localStorage.setItem("workPlan", "{}");
  initValueStr = "{}";
}
let initValue: WorkStore = JSON.parse(initValueStr);
let [workStore, setWorkStore] = createStore(initValue);
let getWorkPlanById = (id: string) => {
  if (!workStore[id]) {
    setWorkStore(id, []);
  }
  return () => workStore[id];
};
let effected = false;
export let useWorkPlanStore = () => {
  if (!effected) {
    createEffect(() => {
      localStorage.setItem("workPlan", JSON.stringify(workStore));
    });
    effected = true;
  }
  return {
    workStore,
    setWorkStore,
    getWorkPlanById,
  };
};

let getDoStateLabel = (doState: doState) =>
  useableState.find(one => one.value === doState)?.label;
let transPlan = (data: PlanItem, prefix = "") => {
  let text = data.text;
  let textArr = text.split("\n").flatMap(one => {
    let might = one.split("\r");
    return might;
  });
  let arr = textArr.map(one => prefix + one);
  if (data.doState) {
    arr[0] += "   " + getDoStateLabel(data.doState);
  }
  if (data.schedulePercent) {
    arr[0] += "   " + data.schedulePercent + "%";
  }
  arr[0] = arr[0].replace(" ", "");
  for (let i = 1; i < arr.length; i++) {
    arr[i] = "   " + arr[i];
  }
  return arr.join("\r\n");
};
export let transPlans = (data: PlanItem[], prefix = "") => {
  return data.map((one, i) => {
    let txt = transPlan(one, prefix);
    return `${prefix}${i + 1}. ${txt}`;
  });
};
